<template>
  <view class="container">
    <!-- 上传头像框 -->
    <view class="avatar-upload" @click="chooseAvatar">
      <!-- 默认头像或用户上传的头像 -->
      <image v-if="avatarUrl" :src="avatarUrl" class="avatar" mode="aspectFill" />
      <view v-else class="avatar-placeholder">
        <text class="avatar-placeholder-text">上传头像</text>
      </view>
    </view>

    <view class="form">
      <view class="input-group">
        <input v-model="username" type="text" placeholder="请输入用户名" class="input-field" />
      </view>
	  <view class="input-group">
	    <input v-model="name" type="text" placeholder="请输入姓名" class="input-field" />
	  </view>
	  <view class="input-group">
	    <label class="gender-label">性别</label>
	    <radio-group :value="sex" @change="handleSexChange" class="radio-group">
	      <radio value="1" class="radio-option">男</radio>
	      <radio value="0" class="radio-option">女</radio>
	    </radio-group>
		<label class="age-label">年龄</label>
		<input v-model="age" type="number" placeholder="请输入年龄" class="age-input" />岁
	  </view>
	  <view class="input-group">
	    <input v-model="address" type="text" placeholder="请输入家庭住址" class="input-field" />
	  </view>
	  <view class="input-group">
	    <input v-model="phoneNumber" type="text" placeholder="请输入联系方式" class="input-field" />
	  </view>
      <view class="input-group">
        <input v-model="password" type="password" placeholder="请输入密码" class="input-field" />
      </view>
      <view class="input-group">
        <input v-model="confirmPassword" type="password" placeholder="确认密码" class="input-field" />
      </view>
      
     <!-- <view class="captcha-group">
        <input v-model="captcha" type="text" placeholder="请输入验证码" class="input-field captcha-input" />
        <canvas id="captchaCanvas" class="captcha-canvas" canvas-id="captchaCanvas" @click="getCaptcha"></canvas>
      </view> -->

      <button @click="onRegister" class="register-btn">注册</button>

      <view class="signup-link">
        <text>已有账号？</text>
        <button @click="onGoToLogin" class="login-btn">登录</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import {
	onLoad
} from '@dcloudio/uni-app';
const app = getApp();
const username = ref('');
const password = ref('');
const confirmPassword = ref('');
const captcha = ref('');
const captchaImg = ref('');
const avatarUrl = ref('');  // 存储头像 URL
const uuid = ref('');
const errorMsg = ref('');
const avatar = ref('')
const sex = ref(1)
const age = ref(null)
const roleKey = ref('')
const name = ref('')
const address = ref('')
const phoneNumber = ref('')

onLoad((options)=>{
	roleKey.value = options.roleKey
	console.log(options)
})

const handleSexChange = (e) => {
  sex.value = e.detail.value;  // 更新性别的值
};

// 获取验证码的函数
const getCaptcha = async () => {
  app.globalData.utils.myrequest({
    myurl: '/captchaImage',
    method: 'GET',
    mysuccess: (res) => {
      if (res.code == 200) {
        captchaImg.value = "data:image/gif;base64," + res.img;
        uuid.value = res.uuid;
        drawCaptcha();
        errorMsg.value = '';
      } else {
        errorMsg.value = res.msg;
      }
    },
    myfail: () => {
      errorMsg.value = '验证码请求失败，请稍后再试';
    }
  });
};

// 绘制验证码
const drawCaptcha = () => {
  const canvas = uni.createCanvasContext('captchaCanvas');
  const canvasWidth = 120;
  const canvasHeight = 48;
  const imgWidth = 100;
  const imgHeight = 40;

  canvas.clearRect(0, 0, canvasWidth, canvasHeight);
  canvas.setStrokeStyle('#dcdcdc');
  canvas.setLineWidth(1);
  canvas.strokeRect(0, 0, canvasWidth, canvasHeight);
  const x = (canvasWidth - imgWidth) / 2;
  const y = (canvasHeight - imgHeight) / 2;
  canvas.drawImage(captchaImg.value, x, y, imgWidth, imgHeight);
  canvas.draw();
};

// 选择头像
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1, // 只选择一个图片
    sizeType: ['original', 'compressed'], // 可以选择原图或压缩图
    sourceType: ['album', 'camera'], // 可以从相册或相机选择
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0];  // 获取图片路径
      avatarUrl.value = tempFilePath;  // 设置头像 URL
      uploadAvatar(tempFilePath);  // 上传头像
    },
    fail: (err) => {
      console.log('选择头像失败', err);
    }
  });
};

// 上传头像
const uploadAvatar = (filePath) => {
  uni.uploadFile({
    url: app.globalData.utils.baseUrl + '/common/upload',  // 替换为实际上传接口
    filePath: filePath,
    name: 'file',  // 后端参数名称
    formData: {
      user: 'test'  // 可以传递额外的参数
    },
    success: (res) => {
      const data = JSON.parse(res.data);
      if (data.code == 200) {
		avatar.value = data.fileName
        uni.showToast({
          title: '头像上传成功',
          icon: 'success',
        });
      } else {
        uni.showToast({
          title: '头像上传失败',
          icon: 'none',
        });
      }
    },
    fail: (err) => {
      uni.showToast({
        title: '头像上传失败',
        icon: 'none',
      });
      console.log('上传头像失败', err);
    }
  });
};

const onRegister = () => {
  if (!username.value || !password.value || !confirmPassword.value) {
    uni.showToast({
      title: '请输入完整信息',
      icon: 'none',
    });
    return;
  }

  if (password.value !== confirmPassword.value) {
    uni.showToast({
      title: '密码不一致',
      icon: 'none',
    });
    return;
  }

  // 注册请求
  app.globalData.utils.myrequest({
    myurl: '/pz/patient/wx/add',
    method: 'POST',
    data: {
      username: username.value,
      password: password.value,
	  name: name.value,
      avatarUrl: avatar.value,  // 传递头像 URL
	  gender: sex.value,
	  age: age.value,
	  roleKey: roleKey.value,
	  address: address.value,
	  phoneNumber: phoneNumber.value
    },
    mysuccess: (res) => {
      if (res.code == 200) {
        uni.showToast({
          title: '注册成功',
          icon: 'success',
        });
        setTimeout(() => {
          uni.redirectTo({
            url: '../../pages/login/index'
          });  // 注册成功后跳转到登录页面
        }, 2000);
      } else {
        uni.showToast({
          title: res.msg,
          icon: 'none',
        });
      }
    },
  });
};

const onGoToLogin = () => {
  uni.redirectTo({
    url: '/pages/login/index'
  });
};

// getCaptcha();
</script>

<style>
	@import url(./index.css);
</style>
